package com.cn.wanxi.servlet.back.product;

import com.cn.wanxi.dao.impl.ProductTypeDaoImpl;
import com.cn.wanxi.dao.impl.UserTypeDaoImpl;
import com.cn.wanxi.model.DataField;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.service.IProductService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.util.DataEncoding;
import com.cn.wanxi.util.Upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/back/product/manage")
public class ProductManageServlet extends HttpServlet {
    IProductService productService = new ProductServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setCharacterEncoding(req,resp);
        DataEncoding.setTextContentType(resp);
        //产品删除
        String pid = req.getParameter("id");
        int id = 0;
        if (pid!=""&&pid!=null)
        id = Integer.parseInt(pid);
        int result = productService.deleteProduct(id);
        resp.getWriter().print(result);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setCharacterEncoding(req,resp);
        DataEncoding.setTextContentType(resp);
        //产品修改
        int id = Integer.parseInt(req.getParameter("id"));
        String name = req.getParameter("name");
        String number =  req.getParameter("price");
        String photo =  req.getParameter("photo");
        String product_type =  req.getParameter("product_type");
        String user_type =  req.getParameter("user_type");
        BigDecimal price = new BigDecimal("0.0");
        String intro = req.getParameter("intro");
        int ptid = Integer.parseInt(product_type);
        int utid = Integer.parseInt(user_type);
        if (!"".equals(number))
            price = new BigDecimal(number);
        ProductModel product = new ProductModel();
        product.setId(id);
        product.setName(name);
        product.setPrice(price);
        product.setPhoto(photo);
        product.setIntro(intro);
        product.setProductType(new ProductTypeDaoImpl().getProductType(ptid));
        product.setUserType(new UserTypeDaoImpl().getUserType(utid));
        product.setUpdate_time(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date().getTime()));
        Upload.UploadOut(product.getPhoto(), DataField.outPath, DataField.basePath);//获取解析后的参数列表
        int result = productService.updateProduct(product);
        System.out.println(result);
        resp.getWriter().print(result);
    }
}
